package one.caravan.theopener.dummy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class FileListAdapter extends BaseAdapter {	
	List<File> files;
	private LayoutInflater inflater;
	private String path;
	private boolean dir;
	
	public FileListAdapter(Context context, String path, boolean dir) {
		this.inflater = LayoutInflater.from(context);		
		this.path = path;
		this.dir = dir;
		refresh();
	}
	
	public void changePath(String path) {
		this.path = path;
		refresh();
	}
	
	public String getCurrentPath() {
		return path;
	}
	
	public File getCurrentFile() {
		return new File(path);
	}
	
	public void refresh() {
		File file = new File(path);
		List<File> files = new ArrayList<File>();
		
		if (file.isDirectory() && file.canRead()) {
			for (File child : file.listFiles()) {
				if (dir) {
					if (child.isDirectory())
						files.add(child);
				} else 					
					files.add(child);
			}
		} else {
			files.add(file);
		}
		
		boolean changed = (this.files == null || this.files.hashCode() != files.hashCode());
		this.files = files;		
		
		if (changed)
			notifyDataSetChanged();
	}
	
	

	@Override
	public int getCount() {
		return files.size();
	}

	@Override
	public File getItem(int position) {
		return files.get(position);
	}
	
	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = inflater.inflate(android.R.layout.simple_list_item_activated_1, null);
			convertView.setTag(convertView.findViewById(android.R.id.text1));
		}
		
		TextView text1 = (TextView) convertView.getTag();
		text1.setText(getItem(position).getName());			
		
		return convertView;
	}	
}
